#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <unistd.h>
#include <time.h>
#include <sys/ipc.h>

void msg_show_attr(int msq_id)
{
    struct msqid_ds msg_info;
    int ret = -1;
    ret = msgctl(msq_id, IPC_STAT, &msg_info);
    if(ret == -1)
    {
        printf("获取消息信息失败\n");
        return;
    }
    printf("\n");
    printf("现有字节数 %ld\n", msg_info.msg_cbytes);
    printf("消息数%ld\n", msg_info.msg_qnum);
    printf("最大字节数 %ld\n", msg_info.msg_qbytes);
    printf("最后发送消息的进程pid %d\n", msg_info.msg_lspid);
    printf("最后接收消息的进程pid %d\n", msg_info.msg_lrpid);
    printf("最后发送消息的时间 %ld\n", msg_info.msg_stime);
    printf("最后接收消息的时间 %ld\n", msg_info.msg_rtime);
    printf("最后变化的时间 %ld\n", msg_info.msg_rtime);
    printf("消息uid是 %d\n", msg_info.msg_perm.uid);
    printf("消息gid是 %d\n", msg_info.msg_perm.gid);

}
struct msgmbuf {
    long mtype;
    char mtext[10];
};
int main()
{
    const char* path = "/home/luan/linux_net/c4";
    int key = ftok(path, 'b');
    if(key == -1)
    {
        printf("ftok error \n");
        return -1;
    }
    int msg_flags  = IPC_CREAT | IPC_EXCL;
    int  msq_id = msgget(key, msg_flags | 0666);
    if(msq_id == -1)
    {
        printf("msgget error\n");
        return -1;
    }
    msg_show_attr(msq_id);
    int msg_sflags = IPC_NOWAIT;

    struct msgmbuf msg_mbuf;
    msg_mbuf.mtype = 10;
    const char* msg_test = "测试消息";
    memcpy(msg_mbuf.mtext, msg_test, strlen(msg_test));
    int ret = msgsnd(msq_id, &msg_mbuf, strlen(msg_test), msg_sflags);
    if(ret == -1)
    {
        printf("发送消息失败\n");
    }

    msg_show_attr(msq_id);
    int msg_rflags = IPC_NOWAIT | MSG_NOERROR;
    struct msgmbuf msg_rmbuf;
    msg_rmbuf.mtype = 10;

    ret = msgrcv(msq_id, &msg_rmbuf, 10, 10, msg_rflags);
    if(ret == -1)
    {
        printf("接收消息失败了\n");
    }
    else
    {
        printf("接收到的消息长度为%d\n", ret);
    }
    msg_show_attr(msq_id);
    struct msqid_ds buf;
    ret = msgctl(msq_id, IPC_STAT, &buf);
    buf.msg_perm.uid = 8;
    buf.msg_perm.gid = 9;
    buf.msg_qbytes = 12345;
    ret = msgctl(msq_id, IPC_SET, &buf);
    msg_show_attr(msq_id);
    ret = msgctl(msq_id, IPC_RMID, NULL);
    printf("结束了\n");
    return 0;
}
